package com.example.common.network;

import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import com.example.common.utils.LogUtil;

public class OkHttpClientManager {
    
    private static volatile OkHttpClientManager instance;
    private OkHttpClient defaultClient;
    
    private OkHttpClientManager() {
        initDefaultClient();
    }
    
    public static OkHttpClientManager getInstance() {
        if (instance == null) {
            synchronized (OkHttpClientManager.class) {
                if (instance == null) {
                    instance = new OkHttpClientManager();
                }
            }
        }
        return instance;
    }
    
    /**
     * 初始化默认客户端
     */
    private void initDefaultClient() {
        defaultClient = createBaseClient(null);
        LogUtil.d("OkHttpClientManager", "Default OkHttpClient initialized");
    }
    
    /**
     * 获取默认OkHttpClient
     */
    public OkHttpClient getOkHttpClient() {
        return defaultClient;
    }
    
    /**
     * 获取带Token刷新功能的OkHttpClient
     */
    public OkHttpClient getOkHttpClient(TokenRefreshInterceptor.TokenRefreshCallback refreshCallback) {
        if (refreshCallback == null) {
            return defaultClient;
        }
        return createBaseClient(refreshCallback);
    }
    
    /**
     * 创建基础OkHttpClient
     */
    private OkHttpClient createBaseClient(TokenRefreshInterceptor.TokenRefreshCallback refreshCallback) {
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .connectTimeout(NetworkConfig.CONNECT_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(NetworkConfig.READ_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(NetworkConfig.WRITE_TIMEOUT, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true);
        
        // 添加Header拦截器（优先级最高）
        builder.addInterceptor(new HeaderInterceptor());
        
        // 添加日志拦截器
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                LogUtil.d("OkHttp", message);
            }
        });
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        builder.addInterceptor(loggingInterceptor);
        
        // 添加Token刷新拦截器（如果提供了回调）
        if (refreshCallback != null) {
            builder.addInterceptor(new TokenRefreshInterceptor(refreshCallback));
        }
        
        return builder.build();
    }
    
    /**
     * 创建自定义配置的OkHttpClient
     */
    public OkHttpClient createCustomClient(int connectTimeout, int readTimeout, int writeTimeout, 
                                         boolean enableLogging, 
                                         TokenRefreshInterceptor.TokenRefreshCallback refreshCallback) {
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .connectTimeout(connectTimeout, TimeUnit.SECONDS)
                .readTimeout(readTimeout, TimeUnit.SECONDS)
                .writeTimeout(writeTimeout, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true);
        
        // 添加Header拦截器
        builder.addInterceptor(new HeaderInterceptor());
        
        // 可选的日志拦截器
        if (enableLogging) {
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                @Override
                public void log(String message) {
                    LogUtil.d("OkHttp", message);
                }
            });
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder.addInterceptor(loggingInterceptor);
        }
        
        // 可选的Token刷新拦截器
        if (refreshCallback != null) {
            builder.addInterceptor(new TokenRefreshInterceptor(refreshCallback));
        }
        
        LogUtil.d("OkHttpClientManager", "Custom OkHttpClient created");
        return builder.build();
    }
}